package com.yxq.mdt.app.modules.order.ui;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ToastUtils;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.modules.bottomsheet.OrderConfirmCouponListBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.OrderConfirmDeliveryMethodBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.OrderConfirmGoodsListBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.OrderConfirmPayMethodBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.goodsdetail.bean.GoodsDetailBean;
import com.yxq.mdt.app.modules.order.bean.ExpressBean;
import com.yxq.mdt.app.modules.order.bean.OrderConfirmBean;
import com.yxq.mdt.app.modules.order.bean.OrderDetailBean;
import com.yxq.mdt.app.modules.order.bean.OrderListBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultBalanceBean;
import com.yxq.mdt.app.modules.order.bean.OrderPayResultWxBean;
import com.yxq.mdt.app.modules.order.bean.OrderSubmitCartBean;
import com.yxq.mdt.app.modules.order.bean.OrderSubmitGoodsBean;
import com.yxq.mdt.app.modules.order.bean.OrderSubmitResult;
import com.yxq.mdt.app.modules.order.model.OrderModel;
import com.yxq.mdt.app.modules.order.prestener.IOrderContract;
import com.yxq.mdt.app.modules.order.prestener.OrderPresenter;
import com.yxq.mdt.app.modules.order.ui.adapter.OrderConfirmGoodsListAdapter;
import com.yxq.mdt.app.modules.personal.bean.AddressListBean;
import com.yxq.mdt.app.modules.personal.model.AddressModel;
import com.yxq.mdt.app.modules.personal.ui.activity.AddressManagerAddActivity;
import com.yxq.mdt.app.modules.personal.ui.activity.MainPersonalShippingAddressAc;
import com.yxq.mdt.app.modules.shoppingcart.bean.CartBean;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 确认订单
 */
public class OrderConfirmActivity extends BaseActivity<OrderPresenter> implements IOrderContract.View {


    @BindView(R.id.address_tv_name)
    TextView addressTvName;
    @BindView(R.id.address_tv_phone)
    TextView addressTvPhone;
    @BindView(R.id.address_tv_address)
    TextView addressTvAddress;
    @BindView(R.id.order_confirm_tv_method)
    TextView orderConfirmTvMethod;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.order_confirm_tv_goods_count)
    TextView orderConfirmTvGoodsCount;
    @BindView(R.id.order_confirm_tv_delivery_method)
    TextView orderConfirmTvDeliveryMethod;
    @BindView(R.id.order_confirm_tv_coupon)
    TextView orderConfirmTvCoupon;
    @BindView(R.id.order_confirm_tv_goods_price)
    TextView orderConfirmTvGoodsPrice;
    @BindView(R.id.order_confirm_tv_delivery_price)
    TextView orderConfirmTvDeliveryPrice;
    @BindView(R.id.order_confirm_et_remark)
    EditText orderConfirmEtRemark;
    @BindView(R.id.cart_tv_hint)
    TextView cartTvHint;
    @BindView(R.id.order_confirm_tv_price)
    TextView orderConfirmTvPrice;
    @BindView(R.id.order_confirm_tv_submit)
    TextView orderConfirmTvSubmit;
    @BindView(R.id.order_confirm_layout_address)
    RelativeLayout orderConfirmLayoutAddress;
    @BindView(R.id.order_confirm_tv_remark_hint)
    TextView orderConfirmTvRemarkHint;
    @BindView(R.id.order_confirm_layout_bottom)
    RelativeLayout orderConfirmLayoutBottom;
    List<CartBean.ListBean> cartBuyGoodsList;
    String from = "";
    OrderConfirmGoodsListAdapter orderConfirmGoodsListAdapter;
    GoodsDetailBean goodsDetailBean;
    int DATA_TYPE = 1;
    OrderConfirmBean orderConfirmBean;
    OrderConfirmBean.MchListBean.CouponListBean couponListBeanChecked;

    @Override
    public int getLayoutId() {
        return R.layout.activity_confirm_order;
    }

    @Override
    public void initView() {
        from = getIntent().getStringExtra("from");
        if ("cart".equals(from)) {
            DATA_TYPE = 1;
            cartBuyGoodsList = JSON.parseArray(getIntent().getStringExtra("data"), CartBean.ListBean.class);
        } else if ("goods".equals(from)) {
            DATA_TYPE = 2;
            goodsDetailBean = JSON.parseObject(getIntent().getStringExtra("data"), GoodsDetailBean.class);
            initGoodsData();
        }
        //getPrice();
        int num = 0;
        for (CartBean.ListBean bean : cartBuyGoodsList) {
            num += bean.getNum();
        }
        orderConfirmTvGoodsCount.setText(String.format("共%d件", num));
        recyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        orderConfirmGoodsListAdapter = new OrderConfirmGoodsListAdapter(R.layout.layout_order_confirm_goods_list_item_layout, cartBuyGoodsList);
        recyclerView.setAdapter(orderConfirmGoodsListAdapter);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(5, 15, false));
    }

    /**
     * 转换商品数据为购物车数据格式
     */
    private void initGoodsData() {
        cartBuyGoodsList = new ArrayList<>();
        if (goodsDetailBean != null) {
            CartBean.ListBean listBean = new CartBean.ListBean();
            listBean.setGoods_name(goodsDetailBean.getName());
            listBean.setGoods_pic(goodsDetailBean.getPic_list().get(0).getPic_url());
            listBean.setUnitPrice(goodsDetailBean.getPrice());
            listBean.setPrice(goodsDetailBean.getPrice());
            listBean.setNum(goodsDetailBean.getNum());
            listBean.setMax_num(2);
            listBean.setChecked(true);
            //构造规格参数
            List<CartBean.ListBean.AttrListBean> attrListBeans = new ArrayList<>();

            int size = goodsDetailBean.getAttr().get(0).getAttr_list().size();
            List<OrderSubmitGoodsBean.GoodsListBean.AttrBean> data = JSON.parseArray(getIntent().getStringExtra("attr"), OrderSubmitGoodsBean.GoodsListBean.AttrBean.class);
            Log.e("商品信息","attr:"+data.size());
            for (int i = 0; i < size; i++) {
                CartBean.ListBean.AttrListBean bean = new CartBean.ListBean.AttrListBean();

                bean.setAttr_name(data.get(i).getAttr_name());
                bean.setAttr_group_name(data.get(i).getAttr_group_name());
                attrListBeans.add(bean);
            }

            listBean.setAttr_list(attrListBeans);

            cartBuyGoodsList.add(listBean);
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new OrderPresenter(this, new OrderModel());
        getAddress();
    }

    /**
     * 获取地址
     */
    private void getAddress() {
        AddressModel addressModel = new AddressModel();
        addressModel.addressList(new ApiModel.CommonCallback<AddressListBean>() {
            @Override
            public void onSuccess(AddressListBean addressListBean) {
                if (addressListBean.getList() != null && addressListBean.getList().size() > 0) {
                    for (AddressListBean.ListBean bean : addressListBean.getList()) {
                        if (bean.getIs_default() == 1) {
                            setAddress(bean);
                            orderPreview(bean.getId());
                            return;
                        }
                    }
                    setAddress(addressListBean.getList().get(0));
                    orderPreview(addressListBean.getList().get(0).getId());
                } else {
                    addressTvAddress.setText("选择地址");
                    orderPreview("");
                }
            }

            @Override
            public void onError(String errMsg) {

            }
        });
    }

    /**
     * 订单预览
     */
    private void orderPreview(String addressId) {
        showLoadingDialog();
        String mchList = "";
        if (DATA_TYPE == 1) {
            //购物车
            OrderSubmitCartBean orderSubmitCartBean = new OrderSubmitCartBean();
            orderSubmitCartBean.setMch_id(0);//商家id 自营为0 我们平台只有自营
            List<OrderSubmitCartBean.GoodsListBean> goodsListListBean = new ArrayList<>();
            for (CartBean.ListBean cart : cartBuyGoodsList) {
                if (cart.isChecked()) {
                    OrderSubmitCartBean.GoodsListBean goodsListBean = new OrderSubmitCartBean.GoodsListBean();
                    goodsListBean.setCart_id(cart.getCart_id());
                    goodsListListBean.add(goodsListBean);
                }
            }
            orderSubmitCartBean.setGoods_list(goodsListListBean);
            List<OrderSubmitCartBean> cartData = new ArrayList<>();
            cartData.add(orderSubmitCartBean);
            mchList = JSON.toJSONString(cartData);
        } else if (DATA_TYPE == 2) {
            //商品
            OrderSubmitGoodsBean orderSubmitGoodsBean = new OrderSubmitGoodsBean();
            orderSubmitGoodsBean.setMch_id(0);//商家id 自营为0 我们平台只有自营
            List<OrderSubmitGoodsBean.GoodsListBean> goodsListListBean = new ArrayList<>();
            OrderSubmitGoodsBean.GoodsListBean goodsListBean = new OrderSubmitGoodsBean.GoodsListBean();
            //商品信息
            goodsListBean.setGoods_id(goodsDetailBean.getId() + "");
            goodsListBean.setNum(goodsDetailBean.getNum());

            List<OrderSubmitGoodsBean.GoodsListBean.AttrBean> attrList = new ArrayList<>();

            List<OrderSubmitGoodsBean.GoodsListBean.AttrBean> data = JSON.parseArray(getIntent().getStringExtra("attr"), OrderSubmitGoodsBean.GoodsListBean.AttrBean.class);
            int size = goodsDetailBean.getAttr().get(0).getAttr_list().size();
            for (int i = 0; i < size; i++) {

                OrderSubmitGoodsBean.GoodsListBean.AttrBean attrBean = new OrderSubmitGoodsBean.GoodsListBean.AttrBean();

                attrBean.setAttr_id(data.get(i).getAttr_id());
                attrBean.setAttr_name(data.get(i).getAttr_name());

                attrBean.setAttr_group_id(data.get(i).getAttr_group_id());
                attrBean.setAttr_group_name(data.get(i).getAttr_group_name());
                attrList.add(attrBean);
            }

            goodsListBean.setAttr(attrList);
            goodsListListBean.add(goodsListBean);
            orderSubmitGoodsBean.setGoods_list(goodsListListBean);
            List<OrderSubmitGoodsBean> cartData = new ArrayList<>();
            cartData.add(orderSubmitGoodsBean);
            mchList = JSON.toJSONString(cartData);
        }
        mPresenter.preview(addressId, mchList);
    }

    @OnClick({R.id.order_confirm_tv_goods_count, R.id.order_confirm_layout_address, R.id.order_confirm_tv_method, R.id.order_confirm_tv_delivery_method, R.id.order_confirm_tv_coupon, R.id.order_confirm_tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.order_confirm_tv_method://支付方式
                OrderConfirmPayMethodBottomSheetDialogFragment orderConfirmPayMethodBottomSheetDialogFragment = new OrderConfirmPayMethodBottomSheetDialogFragment(cartBuyGoodsList);
                orderConfirmPayMethodBottomSheetDialogFragment.show(getSupportFragmentManager(), "OrderConfirmPayMethodBottomSheetDialogFragment");
                break;
            case R.id.order_confirm_tv_delivery_method://配送方式
                OrderConfirmDeliveryMethodBottomSheetDialogFragment orderConfirmDeliveryMethodBottomSheetDialogFragment = new OrderConfirmDeliveryMethodBottomSheetDialogFragment(cartBuyGoodsList);
                orderConfirmDeliveryMethodBottomSheetDialogFragment.show(getSupportFragmentManager(), "OrderConfirmDeliveryMethodBottomSheetDialogFragment");
                break;
            case R.id.order_confirm_tv_coupon://优惠券
                coupon();
                break;
            case R.id.order_confirm_tv_submit://提交
                submitOrder();
                break;
            case R.id.order_confirm_layout_address://收货地址管理
                if (addressTvPhone.getText().toString().length() == 0) {
                    Intent intent = new Intent(mActivity, AddressManagerAddActivity.class);
                    intent.putExtra("from", "order");
                    startActivityForResult(intent, 10086);
                    return;
                }
                Intent intent = new Intent(mActivity, MainPersonalShippingAddressAc.class);
                intent.putExtra("from", "order");
                startActivityForResult(intent, 10086);
                break;
            case R.id.order_confirm_tv_goods_count://商品清单
                OrderConfirmGoodsListBottomSheetDialogFragment orderConfirmGoodsListBottomSheetDialogFragment = new OrderConfirmGoodsListBottomSheetDialogFragment(cartBuyGoodsList);
                orderConfirmGoodsListBottomSheetDialogFragment.show(getSupportFragmentManager(), "OrderConfirmGoodsListBottomSheetDialogFragment");
                break;
        }
    }

    private void coupon() {
        if (orderConfirmTvCoupon.getText().toString().length() == 0) {
            return;
        }
        if (orderConfirmTvCoupon.getText().toString().equals("无")) {
            ToastUtils.showShort("无可用优惠券");
            return;
        }
        if (getOrderConfirmBean() == null) {
            return;
        }
        OrderConfirmCouponListBottomSheetDialogFragment orderConfirmCouponListBottomSheetDialogFragment = new OrderConfirmCouponListBottomSheetDialogFragment(getOrderConfirmBean().getMch_list().get(0).getCoupon_list(), couponListBeanChecked);
        orderConfirmCouponListBottomSheetDialogFragment.show(getSupportFragmentManager(), "OrderConfirmCouponListBottomSheetDialogFragment");
        orderConfirmCouponListBottomSheetDialogFragment.setCouponCheckedInterface(couponListBean -> {
            if (couponListBean == null) {
                return;
            }
            couponListBeanChecked = couponListBean;
            //设置优惠券信息
            orderConfirmTvCoupon.setText("-" + couponListBean.getSub_price());
            //计算使用优惠券后的价格
            float price = getOrderConfirmBean().getMch_list().get(0).getTotal_price() - couponListBean.getSub_price();
            if (price < 0f) {
                //最小价格为0
                price = 0;
            }
            orderConfirmTvPrice.setText(String.format("￥%.2f", price));
        });
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        if (addressTvPhone.getText().toString().length() == 0) {
            ToastUtils.showShort("请先选择收货地址");
            return;
        }
        if (getOrderConfirmBean() == null) {
            return;
        }
        if (getOrderConfirmBean().getMch_list().get(0).getIs_area() == 1) {
            //该区域是否能购买 1-不能购买 0-能购买
            ToastUtils.showShort("该区域不支持购买");
            return;
        }
        if (getOrderConfirmBean().getMch_list().get(0).getOffer_rule().getIs_allowed() == 1) {
            //起送规格 0：允许购买 1不允许购买
            ToastUtils.showShort(getOrderConfirmBean().getMch_list().get(0).getOffer_rule().getMsg());
            return;
        }

        //提交订单
        //支付方式 1在线 2红包 3余额
        List<OrderConfirmBean.MchListBean> mch_list = getOrderConfirmBean().getMch_list();
        OrderConfirmBean.MchListBean mchListBean = mch_list.get(0);

        List<OrderConfirmBean.MchListBean.AttrBean> attrBeanList = new ArrayList<>();
        OrderConfirmBean.MchListBean.AttrBean attrBean = new OrderConfirmBean.MchListBean.AttrBean();
        if (DATA_TYPE == 1) {
            //购物车

        } else if (DATA_TYPE == 2) {
            //商品
            attrBean.setAttr_id(goodsDetailBean.getAttr().get(0).getAttr_list().get(0).getAttr_id());
            attrBean.setAttr_name(goodsDetailBean.getAttr().get(0).getAttr_list().get(0).getAttr_name());
            attrBean.setAttr_group_id(goodsDetailBean.getAttr_group_list().get(0).getAttr_group_id());
            attrBean.setAttr_group_name(goodsDetailBean.getAttr_group_list().get(0).getAttr_group_name());
        }
        attrBeanList.add(attrBean);
        OrderConfirmBean.MchListBean.GoodsListBean goodsListBean = mchListBean.getGoods_list().get(0);
        goodsListBean.setAttr(attrBeanList);
        mchListBean.getGoods_list().set(0, goodsListBean);
        mchListBean.setContent(orderConfirmEtRemark.getText().toString());
        showLoadingDialog();

        mPresenter.submit(getOrderConfirmBean().getAddress().getId(), JSON.toJSONString(mch_list, SerializerFeature.WriteMapNullValue), 1, 1);
    }

    public void setOrderConfirmBean(OrderConfirmBean orderConfirmBean) {
        this.orderConfirmBean = orderConfirmBean;
    }

    public OrderConfirmBean getOrderConfirmBean() {
        return orderConfirmBean;
    }

    /**
     * 订单预览
     *
     * @param orderConfirmBean
     */
    @Override
    public void onLoadSuccess(OrderConfirmBean orderConfirmBean) {
        hideLoadingDialog();
        setOrderConfirmBean(orderConfirmBean);
        setOrderUI(orderConfirmBean);
    }

    /**
     * 设置订单信息
     *
     * @param orderConfirmBean
     */
    private void setOrderUI(OrderConfirmBean orderConfirmBean) {
        List<OrderConfirmBean.MchListBean.GoodsListBean> goodsListBeanList = orderConfirmBean.getMch_list().get(0).getGoods_list();
        double allPrice = 0d;
        for (OrderConfirmBean.MchListBean.GoodsListBean goodsListBean : goodsListBeanList) {
            allPrice += goodsListBean.getPrice();
        }
        orderConfirmTvGoodsPrice.setText(String.format("￥%.2f", allPrice));//商品价格
        orderConfirmTvPrice.setText(String.format("￥%.2f", orderConfirmBean.getMch_list().get(0).getTotal_price() + orderConfirmBean.getMch_list().get(0).getExpress_price()));//订单总价
        orderConfirmTvDeliveryPrice.setText(String.format("￥%.2f", orderConfirmBean.getMch_list().get(0).getExpress_price()));//运费
        int couponSize = orderConfirmBean.getMch_list().get(0).getCoupon_list().size();
        orderConfirmTvCoupon.setText(couponSize > 0 ? String.format("%d张可用", couponSize) : "无");

        if (orderConfirmBean.getMch_list().get(0).getIs_area() == 1) {
            //该区域是否能购买 1-不能购买 0-能购买
            ToastUtils.showShort("该区域不支持购买");
        }
        if (orderConfirmBean.getMch_list().get(0).getOffer_rule().getIs_allowed() == 1) {
            //起送规格 0：允许购买 1不允许购买
            ToastUtils.showShort(orderConfirmBean.getMch_list().get(0).getOffer_rule().getMsg());
        }
    }

    @Override
    public void onLoadFailed(String err) {
        hideLoadingDialog();
        ToastUtils.showShort(err);
    }

    @Override
    public void onLoadListSuccess(OrderListBean orderListBean) {

    }

    @Override
    public void onLoadListFailed(String err) {

    }

    /**
     * 生成订单成功 跳转支付
     *
     * @param orderSubmitResult
     */
    @Override
    public void onSubmitSuccess(OrderSubmitResult orderSubmitResult) {
        hideLoadingDialog();
        Intent intent = new Intent(mActivity, OrderPayActivity.class);
        intent.putExtra("gift", getIntent().getBooleanExtra("gift", false));
        intent.putExtra("orderId", orderSubmitResult.getOrder_id());
        intent.putExtra("price", orderConfirmTvPrice.getText().toString().replaceAll("￥", ""));
        startActivity(intent);
        finish();
    }

    @Override
    public void onSubmitFailed(String err) {
        hideLoadingDialog();
        ToastUtils.showShort(err);
    }

    @Override
    public void onPayBalanceSuccess(OrderPayResultBalanceBean orderPayResultBalanceBean) {

    }

    @Override
    public void onPayBalanceFailed(String err) {

    }

    @Override
    public void onPayWxSuccess(OrderPayResultWxBean orderPayResultWxBean) {

    }

    @Override
    public void onPayWxFailed(String err) {

    }

    @Override
    public void onDetailSuccess(OrderDetailBean listBean) {

    }

    @Override
    public void onDetailFailed(String err) {

    }

    @Override
    public void onExpressSuccess(ExpressBean expressBean) {

    }

    @Override
    public void onExpressFailed(String err) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 10086:
                if (data != null && data.getSerializableExtra("data") != null) {
                    AddressListBean.ListBean addressBean = (AddressListBean.ListBean) data.getSerializableExtra("data");
                    setAddress(addressBean);
                    orderPreview(addressBean.getId());
                }
                break;
        }
    }

    /**
     * 设置地址信息
     *
     * @param addressBean
     */
    private void setAddress(AddressListBean.ListBean addressBean) {
        if (addressBean == null) {
            return;
        }
        addressTvName.setText(addressBean.getName());
        addressTvPhone.setText(addressBean.getMobile());
        addressTvAddress.setText(addressBean.getAddress());

    }
}
